import { Collections } from '/imports/files/fileCollections';

Template.channel_crop_cover.onCreated(function() {
  this.isUploading = new ReactiveVar(false);
});

Template.channel_crop_cover.onRendered(function() {
  $('#crop-channel-cover-content').croppie({
    viewport: {
      width: 400,
      height: 210,
    },
    boundary: {
      width: 500,
      height: 310
    }
  });
});

Template.channel_crop_cover.helpers({
  isUploading: function() {
    return Template.instance().isUploading.get();
  }
});

Template.channel_crop_cover.events({
  'click #upload-channel-cover-submit'(event, instance) {
    let channel_id = instance.data.channel._id;
    $('#crop-channel-cover-content').croppie('result', {
      type: 'base64',
      format: 'jpeg',
      size: {
        width: 800,
        height: 420
      }
    }).then(function(base64) {
      Collections.Images.insert({
        file: base64, // 目标文件
        isBase64: true, // 是否为base64格式
        fileName: 'cover.jpg', // 文件名
        meta: { // 提交至服务端的补充信息
          type: 'channel-cover',
          ownerId: channel_id,
          location: `channels/${channel_id}/cover/`
        },
        onStart() { // 文件上传开始事件
          instance.isUploading.set(true);
        },
        onUploaded() { // 文件上传结束事件
          instance.isUploading.set(false);
          $('#crop-channel-cover-modal').modal('hide');
        }
      });
    });
  }
});